﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using System.Text.RegularExpressions;
using System.Threading;
using System.Net;
using System.IO;
using DataAccess;
using Core;

namespace Core.Concrete
{
    public class AccountManager : Zeus
    {        
        Repository<DataAccess.Usuario> __usuariosRepo { get; set; }
        MembershipProvider __provider { get; set; }
        public AccountManager()
            : base()
        {
            __provider = Membership.Provider;
            if (__usuariosRepo == null) __usuariosRepo = new Repository<Usuario>();
        }
        

        /// <summary>
        /// valida las credenciales de un usuario
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public bool ValidateUser(Core.Forms.Login data)
        {
            if (Regex.IsMatch(data.UserName, TheResources.RegexUtilities.EmailRegexPattern))
                return Membership.ValidateUser(Membership.GetUserNameByEmail(data.UserName), data.Password);
            return Membership.ValidateUser(data.UserName, data.Password);
        }

        public MembershipCreateStatus CreateClient(Core.Forms.ModelViews.NewUser data) {
            MembershipCreateStatus status;
            MembershipUser __user =
                __provider.CreateUser(data.UserName, data.Password, data.Email,
                null, null, true, null, out status);

            switch (status)
            {
                case MembershipCreateStatus.Success:
                    try
                    {
                        DataAccess.Usuario __new = new DataAccess.Usuario()
                        {
                            Apellido = data.Usuario.Apellido,
                            Nombre = data.Usuario.Nombre,
                            Id = new Guid(__user.ProviderUserKey.ToString()),
                            
                            TipoIdentificacion = data.Usuario.TipoIdentificacion,
                            NumeroIdentificacion = data.Usuario.NumeroIdentificacion                            
                        };

                        __usuariosRepo.AddEntity(__new);
                        __usuariosRepo.SaveChanges();

                        //Roles.AddUserToRole(data.UserName, data.Rol);
                    }
                    catch
                    {
                        Membership.DeleteUser(data.UserName);
                        throw;
                    }
                    break;
                default: break;
            }
            return status;
        }

        ///// <summary>
        ///// crea un nuevo usuario
        ///// </summary>
        ///// <param name="userName"></param>
        ///// <param name="password"></param>
        ///// <param name="email"></param>
        ///// <returns></returns>
        //public MembershipCreateStatus CreateAdmin(Core.Forms.Register data)
        //{
        //    MembershipCreateStatus status;
        //    MembershipUser __user =
        //        __provider.CreateUser(data.UserName, data.Password, data.Email,
        //        null, null, true, null, out status);

        //    switch (status)
        //    {
        //        case MembershipCreateStatus.Success:
        //            try
        //            {
        //                DataAccess.Administrador __new = new DataAccess.Administrador()
        //                {
        //                    Apellido = data.SurName,
        //                    Nombre = data.GivenName,
        //                    Id = new Guid(__user.ProviderUserKey.ToString())
        //                };

        //                __adminsRepo.AddEntity(__new);
        //                __adminsRepo.SaveChanges();
                        
        //                Roles.AddUserToRole(data.UserName, "Administrador");
        //            }
        //            catch
        //            {
        //                Membership.DeleteUser(data.UserName);
        //                throw;
        //            }
        //            break;
        //        default: break;
        //    }
        //    return status;
        //}        

        /// <summary>
        /// sing in de un usuario
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="createPersistentCookie"></param>
        public void SignIn(string userName, bool createPersistentCookie)
        {
            if (Regex.IsMatch(userName, TheResources.RegexUtilities.EmailRegexPattern))
                userName = Membership.GetUserNameByEmail(userName);
            FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
        }

        /// <summary>
        /// sing out del usuario que esta logueado
        /// </summary>
        public void SignOut()
        {
            FormsAuthentication.SignOut();
        }

        /// <summary>
        /// envia un email con instrucciones sobre como recuperar la contraseña
        /// </summary>
        /// <param name="id"></param>
        /// <param name="ruta"></param>
        public void RecoverInstructions(Guid id, string ruta)
        {
            String __aux = id.ToString() + "|" + ruta;
            ThreadPool.QueueUserWorkItem(new WaitCallback(AsyncRecoverEmailSent), __aux);
        }

        /// <summary>
        /// cambia el password de un administrador
        /// </summary>
        /// <param name="data"></param>
        //public void ResetPassword(Forms.ResetPassword data)
        //{
        //    MembershipUser __user = Membership.GetUser(data.UserId);
        //    __user.ChangePassword(
        //        __user.ResetPassword(), data.NewPassword);
        //}

        /// <summary>
        /// Setea un nuevo password
        /// </summary>
        /// <param name="id"></param>
        /// <param name="newPassword"></param>
        public void ChangePassword(Guid id, string newPassword)
        {
            MembershipUser __user = Membership.GetUser(id);
            __user.ChangePassword(__user.ResetPassword(), newPassword);
        }

        public string UserRole(Guid id)
        {
            Repository<aspnet_UsersInRole> usuarioRol = new Repository<aspnet_UsersInRole>();

            IQueryable<aspnet_UsersInRole> uR = usuarioRol.GetAllRecords();
            foreach (var usuario in uR)
            {
                if (usuario.UserId.Equals(id))
                    return usuario.aspnet_Role.RoleName;
            }

            return String.Empty;
            //return usuarioRol.GetAllRecords().Where(u => u.UserId.Equals(id)).FirstOrDefault().aspnet_Role.RoleName;
        }

        // statics
        static void AsyncRecoverEmailSent(Object state)
        {
            List<String> _to = new List<String>();
            String __aux = state as String;
            String[] __split = __aux.Split(new char[] { '|' });
            Guid __id = new Guid(__split[0]);
            String __ruta = __split[1];
            AccountManager __bll = new AccountManager();
            //DataAccess.U_Administrator __admin =
            //    __bll.GetAdministrador(__id);

            //if (__admin != null)
            //{
            //    try
            //    {
            //        // enviar correo electronico al cliente.
            //        WebRequest __request = WebRequest.Create(__ruta);
            //        WebResponse __response = __request.GetResponse();
            //        __response = __request.GetResponse();
            //        Stream __stream = __response.GetResponseStream();
            //        StreamReader __reader = new StreamReader(__stream);

            //        // enviar correo eletronico a los administradores                
            //        MyHelpers.Email.Email __send = new MyHelpers.Email.Email();
            //        __send.From = System.Configuration.ConfigurationManager.AppSettings["EmailSender"];
            //        __send.To = new List<string>() { __admin.aspnet_Membership.LoweredEmail };
            //        __send.Subject = "Reset your Arrivalo's password";
            //        __send.Cuerpo = __reader.ReadToEnd();
            //        __reader.Close();
            //        __response.Close();
            //        __send.SendEmailMessage(__send.From, __send.To, __send.Subject, __send.Cuerpo);
            //    }
            //    catch { }
            //    finally { }
            //}
        }

        // TODO
        public void AddAvatar(System.Web.HttpPostedFileBase file, Guid id)
        {
            //throw new NotImplementedException();
        }

        //public DataAccess.U_Avatar GetAvatar(Guid id)
        //{
        //    return new DataAccess.U_Avatar()
        //    {
        //        UserId = id
        //    };
        //}     

    }
}
